package jsyf.oa.service.business;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.oa.dao.business.*;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.business.*;
import jsyf.oa.entity.system.UserEntity;
import jsyf.oa.facade.business.BusinessTrustTrialFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;

/**
 * Created by Maqiuqiu on 2018/6/12.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class BusinessTrustTrialService implements BusinessTrustTrialFacade {
    @Autowired
    private BusinessTrustTrialDao businessTrustTrialDao;
    @Autowired
    private TrustTrialAttachDao trustTrialAttachDao;
    @Autowired
    private BusinessMainDao businessMainDao;
    @Autowired
    private BusinessReceiverDao receiverDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private BusinessAuditDao businessAuditDao;
    @Autowired
    private BusinessCopierDao businessCopierDao;

    @Override
    public String save(String jsonData) {
        BusinessEntity model = JSON.toJavaObject(JSON.parseObject(jsonData), BusinessEntity.class);
        Integer rows;
        //第一步，保存主表信息
        BusinessMainEntity entity = model.getMain();
        BusinessMainEntity businessMainEntity = (BusinessMainEntity) businessMainDao.getIBaseEntityById(entity.getId());
        businessMainEntity.setTrustTrialResultName(entity.getTrustTrialResultName());
        businessMainEntity.setTrustTrialResultUrl(entity.getTrustTrialResultUrl());
        businessMainEntity.setTrustTrialReason(entity.getTrustTrialReason());
        businessMainEntity.setTrustTrialFlag(entity.getTrustTrialFlag());
        businessMainEntity.setCustomerInformationName(entity.getCustomerInformationName());
        businessMainEntity.setCustomerInformationUrl(entity.getCustomerInformationUrl());
        rows = businessMainDao.update(businessMainEntity);
        //保存其他附件信息
        trustTrialAttachDao.removeByCondition(" and  MAIN_ID=?", new String[]{entity.getId()});
        List<TrustTrialAttachEntity> attachEntityList = model.getAttachs();
        for (int i = 0; i < attachEntityList.size(); i++) {
            TrustTrialAttachEntity trialAttachEntity = attachEntityList.get(i);
            trialAttachEntity.setMainId(entity.getId());
            trustTrialAttachDao.add(trialAttachEntity);
        }

       /* BusinessTrustTrialEntity entity = model.getMain();
        entity.setTrustTrialTime(businessTrustTrialDao.getCurrentTime());
        if ("0".equals(entity.getId()) || StringUtils.isBlank(entity.getId())) {
            rows = businessTrustTrialDao.add(entity);
        } else {
            BusinessTrustTrialEntity businessTrustTrialEntity = (BusinessTrustTrialEntity) businessTrustTrialDao.getIBaseEntityById(entity.getId());
            businessTrustTrialEntity.setMainId(entity.getMainId());
            businessTrustTrialEntity.setTrustTrialId(entity.getTrustTrialId());
            businessTrustTrialEntity.setTrustTrialName(entity.getTrustTrialName());
            businessTrustTrialEntity.setTrustTrialFlag(entity.getTrustTrialFlag());
            businessTrustTrialEntity.setTrustTrialTime(businessTrustTrialDao.getCurrentTime());
            businessTrustTrialEntity.setTrustTrialAdvise(entity.getTrustTrialAdvise());
            rows = businessTrustTrialDao.update(businessTrustTrialEntity);
        }
        //主表保存信审状态
        BusinessMainEntity businessMainEntity = (BusinessMainEntity) businessMainDao.getIBaseEntityById(entity.getMainId());
        businessMainEntity.setTrustTrialFlag(Integer.valueOf(entity.getTrustTrialFlag()));
        businessMainDao.update(businessMainEntity);
        UserEntity userEntity = userDao.getById(businessMainEntity.getCreateUserId());
        //保存其他附件信息
        trustTrialAttachDao.removeByCondition(" and  TRUST_ID=?", new String[]{entity.getId()});
        List<TrustTrialAttachEntity> attachEntityList = model.getTrusts();
        for (int i = 0; i < attachEntityList.size(); i++) {
            TrustTrialAttachEntity trialAttachEntity = attachEntityList.get(i);
            trialAttachEntity.setMainId(entity.getId());
            trustTrialAttachDao.add(trialAttachEntity);
        }
        //信审成功之后给申请人发送消息
        if (businessMainEntity.getTrustTrialFlag() == 1) {
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", businessMainEntity.getCreateUserId());
            msgObject.put("content", String.format(BUSINESS_TRUST_PASS,
                    userEntity.getName(),
                    businessMainEntity.getModelName(),
                    businessMainEntity.getDealPrice() + " (" + businessMainEntity.getBuyType() + ")",
                    entity.getTrustTrialName(),
                    DateUtils.parse(entity.getTrustTrialTime(), "yyyy-MM-dd HH:mm")));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }
        if (businessMainEntity.getTrustTrialFlag() == 2) {
            JSONObject msgObject = new JSONObject();
            //驳回
            msgObject.put("content", String.format(BUSINESS_AUDIT_REJECT,
                    userEntity.getName(),
                    businessMainEntity.getModelName(),
                    businessMainEntity.getDealPrice() + " (" + businessMainEntity.getBuyType() + ")",
                    entity.getTrustTrialAdvise(),
                    entity.getTrustTrialName(),
                    DateUtils.parse(entity.getTrustTrialTime(), "yyyy-MM-dd HH:mm")));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }
        //保存历史驳回原因信息
        BusinessReceiverEntity receiverEntity = new BusinessReceiverEntity();
        receiverEntity.setMainId(entity.getMainId());
        receiverEntity.setAuditId(entity.getTrustTrialId());
        receiverEntity.setAuditName(entity.getTrustTrialName());
        receiverEntity.setAuditFlag(entity.getTrustTrialFlag());
        receiverEntity.setAuditAdvise(entity.getTrustTrialAdvise());
        receiverEntity.setAuditType(2);
        receiverEntity.setAuditTime((trustTrialAttachDao.getCurrentTime()));
        receiverDao.add(receiverEntity);*/
        return rows == 0 ? "" : entity.getId();
    }

    @Override
    public JSONObject getById(String jsonData) {
        JSONObject jsonObject = JSON.parseObject(jsonData);
        String id = jsonObject.getString("id");
        BusinessEntity businessEntity = new BusinessEntity();
        businessEntity.setMain(JSON.toJavaObject(this.businessMainDao.getViewJSONById(id), BusinessMainEntity.class));
        businessEntity.setReceivers(this.receiverDao.getEntityListByCondition(" AND MAIN_ID =? AND AUDIT_FLAG=2 ORDER BY AUDIT_TIME DESC", new Object[]{id}));
        businessEntity.setTrusts(this.businessTrustTrialDao.getEntityListByCondition(" AND MAIN_ID =?  ORDER BY TRUST_TRIAL_SORT ", new Object[]{id}));
        businessEntity.setAttachs(this.trustTrialAttachDao.getEntityListByCondition(" AND MAIN_ID =? ", new Object[]{id}));
        return (JSONObject) JSON.toJSON(businessEntity);
    }

    @Override
    public Boolean applyAudit(String jsonData) {
        JSONObject jsonObject = JSON.parseObject(jsonData);
        String id = jsonObject.getString("id");
        String userId = jsonObject.getString("userId");
        String userName = jsonObject.getString("userName");
        String auditFlag = jsonObject.getString("auditFlag");
        String advise = jsonObject.getString("advise");
        //保存历史驳回原因信息
        BusinessReceiverEntity receiverEntity = new BusinessReceiverEntity();
        receiverEntity.setMainId(id);
        receiverEntity.setAuditId(userId);
        receiverEntity.setAuditName(userName);
        receiverEntity.setAuditFlag(auditFlag);
        receiverEntity.setAuditAdvise(advise);
        receiverEntity.setAuditType(2);
        receiverEntity.setAuditTime((trustTrialAttachDao.getCurrentTime()));
        receiverDao.add(receiverEntity);
        //根据id获取主表信息
        BusinessMainEntity mainEntity = businessMainDao.getEntityById(id);
        UserEntity userEntity = userDao.getById(mainEntity.getCreateUserId());
        //根据id获取审核信息
        List<BusinessTrustTrialEntity> auditEntityList = businessTrustTrialDao.getEntityListByCondition(" AND MAIN_ID = ? ORDER BY TRUST_TRIAL_SORT ", new Object[]{id});
        BusinessTrustTrialEntity auditEntityNow = null;
        for (int i = 0; i < auditEntityList.size(); i++) {
            if (auditEntityList.get(i).getTrustTrialId().equals(userId)) {
                //如果审核人==当前审核人
                auditEntityNow = auditEntityList.get(i);
                auditEntityNow.setTrustTrialFlag(auditFlag);
                auditEntityNow.setTrustTrialTime(businessTrustTrialDao.getCurrentTime());
                auditEntityNow.setTrustTrialAdvise(advise);
                businessTrustTrialDao.update(auditEntityNow);
                //企业号:发消息通知申请人  (不发送给抄送人)
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", mainEntity.getCreateUserId());
                if ("2".equals(auditFlag)) {
                    //驳回
                    msgObject.put("content", String.format(BUSINESS_AUDIT_REJECT,
                            userEntity.getName(),
                            mainEntity.getModelName(),
                            mainEntity.getDealPrice() + " (" + mainEntity.getBuyType() + ")",
                            auditEntityNow.getTrustTrialAdvise(),
                            auditEntityNow.getTrustTrialName(),
                            DateUtils.parse(auditEntityNow.getTrustTrialTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                }

                if ("1".equals(auditFlag)) {
                    if (i == auditEntityList.size() - 1) {
                        //如果是最后一个审核人
                        mainEntity.setTrustTrialFlag(1);
                        mainEntity.setTrustTrialName("");
                        mainEntity.setTrustTrialId("");
                        businessMainDao.update(mainEntity);
                        //企业号：审核通过之后信审人员接受消息
                        JSONObject msgNextObject = new JSONObject();
                        msgNextObject.put("userIds", mainEntity.getTrustTrialId());
                        msgNextObject.put("content", String.format(BUSINESS_TRUST_AUDIT,
                                mainEntity.getTrustTrialName(),
                                mainEntity.getModelName(),
                                mainEntity.getDealPrice() + " (" + mainEntity.getBuyType() + ")",
                                userEntity.getName(),
                                DateUtils.parse(mainEntity.getCreateTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgNextObject));

                    } else {
                        BusinessTrustTrialEntity auditEntityNext = auditEntityList.get(i + 1);
                        auditEntityNext.setTrustTrialFlag("0");
                        businessTrustTrialDao.update(auditEntityNext);

                        mainEntity.setTrustTrialId(auditEntityNext.getTrustTrialId());
                        String[] arrAuditorName = auditEntityNext.getTrustTrialName().split("-");
                        mainEntity.setTrustTrialName(arrAuditorName[arrAuditorName.length - 1]);
                        mainEntity.setTrustTrialFlag(0);
                        businessMainDao.update(mainEntity);

                        //企业号: 审核通过,发送消息给申请人
                        msgObject.put("userIds", mainEntity.getCreateUserId());
                        msgObject.put("content", String.format(BUSINESS_AUDIT_PASS,
                                userEntity.getName(),
                                mainEntity.getModelName(),
                                mainEntity.getDealPrice() + " (" + mainEntity.getBuyType() + ")",
                                auditEntityNow.getTrustTrialName(),
                                DateUtils.parse(auditEntityNow.getTrustTrialTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                    }
                } else {
                    mainEntity.setTrustTrialFlag(Integer.valueOf(auditFlag));
                    mainEntity.setCurrentAuditorId("");
                    mainEntity.setCurrentAuditorName("");
                    businessMainDao.update(mainEntity);
                }
                break;
            }
        }
        return true;
    }

    @Override
    public Boolean delById(String id) {
        return businessTrustTrialDao.delById(id) > 0;
    }
}
